#include <Constants.au3>

#include-once
Global Const $MSGBOX_TITLE = "飞狐"
Global Const $PORT_ROCKETMQ = 9876
Global Const $PORT_REDIS = 6379
Global Const $PORT_MYSQL=3306
Global Const $CATALINA_HOME = EnvGet("CATALINA_HOME")
Global Const $SERVER_FILE_PATH = $CATALINA_HOME & "\conf\server.xml" ;
Global Const $SERVER_FILE_BAK_PATH = $CATALINA_HOME & "\conf\server.xml.bak" ;

;~ 返回结果：
;~ 成功：返回获取到的端口数组 一般只需要取第一个即可
;~ 失败： @error 为1 CATALINA_HOME不存在 ，@error为2 打开配置文件失败
Func _GetTomcatConfig()
	Local $CATALINA_HOME = EnvGet("CATALINA_HOME")
	If Not $CATALINA_HOME Then
		;MsgBox($MB_SYSTEMMODAL+$MB_ICONWARNING,$MSGBOX_TITLE,"无法确定服务路径,请确认飞狐服务是否已安装")
		Return SetError(1,0,0)
	EndIf
	Local $SERVER_FILE_PATH = $CATALINA_HOME & "\conf\server.xml" ;
	;读文件
	Local $serverFile = FileOpen($SERVER_FILE_PATH, $FO_READ)
	If $serverFile == -1 Then
		;MsgBox($MB_SYSTEMMODAL+$MB_ICONWARNING,$MSGBOX_TITLE,"打开server.xml文件失败")
		Return SetError(2,0,0)
	EndIf
	Local $serverFileText = FileRead($serverFile)
	FileClose($serverFile)
	Return $serverFileText
EndFunc   ;==>_GetTomcatConfig

;~ 返回结果：
;~ 成功：返回获取到的端口数组 一般只需要取第一个即可
;~ 失败： @error为1 CATALINA_HOME不存在 ，@error为2 打开配置文件失败 @error为3 提取端口失败
Func _GetTomcatPort()
	Local $serverFileText = _GetTomcatConfig()

	If @error == 1 Or @error == 2 Then
		Return SetError(@error,0,0)
	EndIf
	Local $oldPort = StringRegExp($serverFileText, "port=""(\d+)""\s+protocol=""HTTP/1.1""", $STR_REGEXPARRAYMATCH)
	If UBound($oldPort) == 0 Then
		Return SetError(3,0,0)
	EndIf
	Return $oldPort[0]
EndFunc   ;==>_GetTomcatPort
Func _GetProgress($port)
	Local $Array[0][3]
	Local $sOutput = _GetDOSOutput("netstat /aon|findstr /R ""TCP.*:" & $port & ".*LISTENING\d*""")
	Local $i = 0
	For $line In StringSplit($sOutput, @CRLF, $STR_ENTIRESPLIT)
		$progressId = StringRegExp($line, "TCP.*:" & $port & "\D+?.+?\s+?LISTENING\s+(\d*)", $STR_REGEXPARRAYMATCH)
		If UBound($progressId) == 1 Then
			$progressInfoLine = _GetDOSOutput("tasklist /NH /FI ""PID eq " & $progressId[0] & """")
			$progressInfo = StringRegExp($progressInfoLine, "(.+?)\s+(\d+).*\d+.*", $STR_REGEXPARRAYMATCH)
			;_ArrayDisplay($progressInfo)
			;_ArrayAdd($array, $progressInfo)
			ReDim $Array[$i + 1][3]
			$Array[$i][0] = $progressInfo[0]
			$Array[$i][1] = $progressInfo[1]
			$Array[$i][2] = $port
			$i += 1
		EndIf
	Next
	;_ArrayDisplay($array)
	Return $Array
EndFunc   ;==>_GetProgress

Func _GetDOSOutput($sCommand)
	Local $iPID, $sOutput = ""
	$iPID = Run('"' & @ComSpec & '" /c ' & $sCommand, "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD)
	While 1
		$sOutput &= StdoutRead($iPID, False, False)
		If @error Then
			ExitLoop
		EndIf
		Sleep(10)
	WEnd
	Return $sOutput
EndFunc   ;==>_GetDOSOutput